package com.minyifang.wcspf.work.ui.user.activities;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.minyifang.wcspf.R;
import com.minyifang.wcspf.common.base.BaseMvpActivity;
import com.minyifang.wcspf.common.utils.ToastHelper;
import com.minyifang.wcspf.work.ui.home.model.CheckRecordBean;
import com.minyifang.wcspf.work.ui.home.model.SignDataBean;
import com.minyifang.wcspf.work.ui.user.presenter.DailySignPresenter;
import com.minyifang.wcspf.work.ui.user.view.DailySignView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 签到
 */
public class DailySignActivity extends BaseMvpActivity<DailySignView, DailySignPresenter> implements DailySignView {

    @BindView(R.id.rv_calendar)
    RecyclerView mRvCalendar;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.tv_sign_rule)
    TextView mTvSignRule;
    @BindView(R.id.sr_refresh)
    SwipeRefreshLayout mRefreshLayout;
    @BindView(R.id.ll_container)
    LinearLayout mLlContainer;

    @BindView(R.id.tv_sign)
    TextView mTvSign;

    List<String> mStringList = new ArrayList<>();
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    private SignDataBean mSignDataBean = new SignDataBean();
    private CalendarAdapter mCalendarAdapter;

    @Override
    protected int setContentLayoutRes() {
        return R.layout.activity_daily_sign;
    }

    @Override
    protected void initView() {
        mRefreshLayout.setOnRefreshListener(this::getData);
        mCalendarAdapter = new CalendarAdapter();
        mRvCalendar.setAdapter(mCalendarAdapter);
        mRvCalendar.setLayoutManager(new GridLayoutManager(this, 7));
    }

    private void resetRefreshLayout() {
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    protected void initData() {
        getData();
    }

    @Override
    protected DailySignPresenter createPresenter() {
        return new DailySignPresenter();
    }

    @Override
    public void showLoadingView() {

    }

    @Override
    public void hideLoadingView() {

    }

    @Override
    public void onNetworkError() {
        resetRefreshLayout();
    }

    @OnClick(R.id.fl_btn_container)
    void fl_btn_container() {
        mPresenter.insertCheckRecord();
    }

    @Override
    public void onRequestFailed(String message) {
        ToastHelper.getInstance(this).showWarn(message);
    }

    @Override
    public void onGetCheckRecordListSucceed(SignDataBean signDataBean) {
        mTvSign.setText(signDataBean.getIsSign() == 0 ? "签到" : "今日已签到");
        ValueAnimator animator = ValueAnimator.ofFloat(1, 1.05f, 1);
        animator.addUpdateListener(animation -> {
            float progress = (float) animation.getAnimatedValue();
            mLlContainer.setScaleX(progress);
            mLlContainer.setScaleY(progress);
            mLlContainer.setAlpha(1 - progress + 1f);
        });
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(300);
        animator.start();
        resetRefreshLayout();
        mSignDataBean = signDataBean;
        Calendar instance = Calendar.getInstance();
        try {
            instance.setTime(mSimpleDateFormat.parse(signDataBean.getDay()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        instance.set(Calendar.DATE, 1);
        int offset = instance.get(Calendar.DAY_OF_WEEK) - 1;
        int maxDays = instance.getMaximum(Calendar.DATE);
        mStringList.clear();
        for (int i = 0; i < offset + signDataBean.getMonthlist().size(); i++) {
            if (i < offset)
                mStringList.add("");
            else
                mStringList.add(String.valueOf(signDataBean.getMonthlist().get(i - offset).getDay()));
        }

        if (mStringList.size() % 7 != 0) {
            int row = mStringList.size() / 7 + 1;
            for (int i = mStringList.size(); i < row * 7; i++) {
                mStringList.add("");
            }
        }

        mTvDate.setText(mSignDataBean.getDay());
        mTvSignRule.setText(mSignDataBean.getRule());

        mCalendarAdapter.notifyDataSetChanged();
    }

    @Override
    public void onCheckSucceed(CheckRecordBean checkRecordBean) {
        getData();
        new Dialog(this) {
            private ImageView mImageView;

            @SuppressLint("SetTextI18n")
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                WindowManager.LayoutParams params = getWindow().getAttributes();
                params.width = WindowManager.LayoutParams.MATCH_PARENT;
                params.height = WindowManager.LayoutParams.MATCH_PARENT;
                getWindow().setAttributes(params);
                getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                View layout = getLayoutInflater().inflate(R.layout.dialog_sign_suceess, null);
                TextView tvSignNum = layout.findViewById(R.id.tv_sign_num);
                TextView tvIntegral = layout.findViewById(R.id.tv_sign_integral);
                mImageView = layout.findViewById(R.id.iv_image);
                mImageView.setScaleX(.5f);
                mImageView.setScaleY(.5f);
                TextView tvTips = layout.findViewById(R.id.tv_sign_tips);
                tvSignNum.setText(Html.fromHtml("您已连续签到" + "<font color=\"#ffff00\">" + checkRecordBean.getCheckrecordcount() + "</font>" + "天"));
                tvIntegral.setText("积分" + checkRecordBean.getEndIntegral());
                tvTips.setText(Html.fromHtml("再连续签到" + "<font color=\"#ffff00\">" + checkRecordBean.getLastDay() + "</font>" + "天，可额外获得积分" + "<font color=\"#ffff00\">" + checkRecordBean.getLastIntegral() + "</font>"));
                setContentView(layout);
                setOnShowListener(dialog -> mImageView.animate().scaleX(1f).scaleY(1f).setDuration(300).start());
            }
        }.show();
    }

    private void getData() {
        mPresenter.getCheckRecordList();
    }

    class CalendarAdapter extends RecyclerView.Adapter<CalendarAdapter.Holder> {

        public CalendarAdapter() {
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Holder holder = new Holder(LayoutInflater.from(DailySignActivity.this).inflate(R.layout.item_calendar, parent, false));
            holder.itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
                    layoutParams.height = holder.itemView.getWidth();
                    holder.itemView.setLayoutParams(layoutParams);
                    holder.itemView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int position) {
            holder.tvTitle.setText(mStringList.get(position));
            holder.vMark.setVisibility(View.GONE);
            if (!mStringList.get(position).equals("")) {
                int offset = mStringList.size() - mSignDataBean.getMonthlist().size();
                if (mSignDataBean.getMonthlist().get(position - offset + 1).getIscheck() == 1) {
                    holder.vMark.setVisibility(View.VISIBLE);
                }
            }
        }

        @Override
        public int getItemCount() {
            return mStringList.size();
        }

        public class Holder extends RecyclerView.ViewHolder {
            TextView tvTitle;
            View vMark;

            public Holder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_title);
                vMark = itemView.findViewById(R.id.v_mark);
            }
        }
    }
}
